<?php
header("content-type:text/html;charset=utf-8");

include_once "0.1conn.php"; //连接数据库

session_start();
$shop_id = $_SESSION['user']['shop_id'];
$goodid = $_POST['goodid'];
$number = $_POST['number'];
$query = "SELECT * FROM clothes WHERE good_id = '$goodid' AND shop_id = '$shop_id' ";
if (mysqli_num_rows(mysqli_query($conn, $query))) {
    $query = "UPDATE clothes SET num = num+$number WHERE good_id = '$goodid' AND shop_id = '$shop_id'";
    mysqli_query($conn, $query);
    //读取缺货单，修改缺货单
    $query = "SELECT * FROM lack_record WHERE good_id = '$goodid' AND shop_id = '$shop_id'";
    $result = mysqli_query($conn, $query);
    if (mysqli_num_rows($result)) {
        $lack = mysqli_fetch_assoc($result);
        if ($number >= $lack['lack_num']) {
            $query = "DELETE FROM lack_record WHERE good_id = '$goodid' AND shop_id = '$shop_id'";
            mysqli_query($conn, $query);
        } else {
            $query = "UPDATE lack_record SET lack_num = lack_num-$number WHERE good_id = '$goodid' AND shop_id = '$shop_id'";
            mysqli_query($conn, $query);
        }
    }
    echo json_encode(array('status' => 'yes'));
} else {
    $style = $_POST['style'];
    $color = $_POST['color'];
    $size = $_POST['size'];
    $price = $_POST['price'];
    $discount = $_POST['discount'];
    if ($style == '' || $color == '' || $size == '' || $price == '' || $discount == '') {
        echo json_encode(array('status' => 'no'));
    } else {
        $query = "INSERT INTO clothes (good_id,num,style,color,size,single_price,discount,shop_id)
            values ('$goodid','$number','$style','$color','$size','$price','$discount','$shop_id')";
        mysqli_query($conn, $query);
        //读取缺货单，修改缺货单
        $query = "SELECT * FROM lack_record WHERE good_id = '$goodid' AND shop_id = '$shop_id'";
        $result = mysqli_query($conn, $query);
        if (mysqli_num_rows($result)) {
            $lack = mysqli_fetch_assoc($result);
            if ($number >= $lack['$goodid']) {
                $query = "DELETE * FROM lack_record WHERE good_id = '$goodid' AND shop_id = '$shop_id'";
                mysqli_query($conn, $query);
            } else {
                $query = "UPDATE lack_record SET lack_num = lack_num-$number WHERE good_id = '$goodid' AND shop_id = '$shop_id'";
                mysqli_query($conn, $query);
            }
        }
        echo json_encode(array('status' => 'yes'));
    }
}

mysqli_close($conn);
